package com.example.es.api;

import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.net.HostAndPort;


import java.util.Iterator;
import java.util.List;

/**
 * Created by yanlei on 2017/7/9.
 */
public class ESConfig {
    private String clusterName = EsConstant.ES_CLUSTER_NAME;
    private String ipAndPorts = EsConstant.ES_HOST_PORT;

    public String getIpAndPorts() {
        return ipAndPorts;
    }

    public void setIpAndPorts(String ipAndPorts) {
        this.ipAndPorts = ipAndPorts;
    }

    public String getClusterName() {
        return clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public List<HostAndPort> getHostAndPortList() {

        if (ipAndPorts == null || ipAndPorts.trim().length() == 0) {
            throw new IllegalArgumentException("ESConfig.ipAndPorts is empty");
        } else {

            if (this.ipAndPorts.indexOf(";") != -1) {
                Iterator<HostAndPort> hostAndPortIterator =  Iterators.transform(Splitter.on(';').split(this.ipAndPorts).iterator(), new Function<String, HostAndPort>() {

                    @Override
                    public HostAndPort apply(String input) {
                        HostAndPort hostAndPort = HostAndPort.fromString(input);
                        return hostAndPort;
                    }
                });
                return Lists.newArrayList(hostAndPortIterator);
            } else {
                HostAndPort hostAndPort = HostAndPort.fromString(this.ipAndPorts);

                return Lists.newArrayList(hostAndPort);
            }
        }
    }

    public void validate(){
        if(this.clusterName == null || this.clusterName.trim().length()==0){
            throw new IllegalArgumentException("ESConfig.clusterName is null");
        }else if (ipAndPorts == null || ipAndPorts.trim().length() == 0) {
            throw new IllegalArgumentException("ESConfig.ipAndPorts is empty");
        }


    }

}
